/**
 * 
 */
package com.monte.export.txt;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import org.apache.commons.beanutils.BeanUtilsBean;

import com.monte.export.Column;
import com.monte.export.Configure;
import com.monte.export.DataPage;
import com.monte.export.ExportDataSource;
import com.monte.export.SimpleExportor;

/**
 * @author fengmengyue
 *
 */
public class TxtDataExportor<T> extends SimpleExportor<T> {
	private String split = "\t";
	public TxtDataExportor(ExportDataSource<T> dataSource,
			OutputStream outputStream, Configure configure,String split) {
		super(dataSource, outputStream, configure);
		if(split == null){
			split = this.split;
		}
		this.setSplit(split);
	}

	@Override
	protected void startExport() throws IOException {
		DataPage<T> dataPage = new DataPage<T>();
		dataPage.setPageSize(configure.getPageSize());
		List<T> datas;
		writeHead();//写列头
		int index = 1;
		do{
			dataPage.setCurrentPage(dataPage.getNextPage());
			dataPage = getDataPage(dataPage);
			datas = dataPage.getDatas();
			if(dataPage.getTotalCount() < datas.size()){
				dataPage.setTotalCount(datas.size());
			}
			for(int i = 0; i < datas.size(); i++){
				writeLine(datas.get(i), index);
				index ++;
			}
			if(index % 1000 == 0){
				outputStream.flush();
			}
			//当还有下一页时，继续取数
		}while(dataPage.getNextPage() > dataPage.getCurrentPage());
		outputStream.flush();
	}
	
	protected void writeLine(Object data,int index) throws IOException{
		List<Column> columns = configure.getColumns();
		StringBuilder line = new StringBuilder();
		if(configure.isIndex()){
			line.append(split).append(index);
		}
		Object fieldValue;
		try{
			for(int i = 0; i < columns.size(); i++){
				fieldValue = BeanUtilsBean.getInstance().getPropertyUtils().getProperty(data, columns.get(i).getFieldName());
				line.append(split).append(fieldValue == null?"":fieldValue.toString());
			}
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		line.append("\n");
		outputStream.write(line.substring(split.length()).getBytes());
	}
	
	protected void writeHead() throws IOException{
		List<Column> columns = configure.getColumns();
		StringBuilder head = new StringBuilder();
		if(configure.isIndex()){
			head.append(split).append("序号");
		}
		for(int i = 0; i < columns.size(); i++){
			head.append(split).append(columns.get(i).getHeadName());
		}
		head.append("\n");
		outputStream.write(head.substring(split.length()).getBytes());
	}

	public void setSplit(String split) {
		this.split = split;
	}

	public String getSplit() {
		return split;
	}
}
